import argparse


from typing import List, Optional, Tuple
from dataclasses import dataclass
from openpyxl import load_workbook


@dataclass
class Resident:
    building: str
    leader: str
    room: str
    name: str
    gender: str
    id_no: str
    age: int
    phone_no: str

def parse_sheet(sheet)-> Optional[Tuple[List[Resident], List[str]]]:
    '''
    行从2开始
    列从1开始
    '''

    residents = []
    invalid_residents = []

    room_phone_dict = {}
    building_no_end_index = sheet.title.find('号')
    if building_no_end_index > 0:
        building_no = sheet.title[:building_no_end_index]
        left_bracket_index = sheet.title.find('（')
        right_bracket_index = sheet.title.find('）')
        leader = sheet.title[left_bracket_index+1:right_bracket_index]
    else:
        return None

    last_room = ''

    for i, row in enumerate(sheet.rows):
        if i < 2:
            continue
        row_list = list(row)

        index = row_list[0].value
        if not index or not str(index):
            # print(f'break {index}')
            continue

        room = row_list[1].value
        if not room:
            #print(f'room = {room}, last_room={last_room}')
            room = last_room
        else:
            last_room = room

        name = row_list[2].value
        gender = row_list[3].value
        id_no = row_list[4].value
        if not id_no or len(str(id_no)) != 18:
            #print('continue 1')
            invalid_residents.append(f'{building_no}号{room}-{name}')
            continue
        try:
            age = int(row_list[5].value)
        except Exception as e:
            invalid_residents.append(f'{building_no}号{room}-{name}')
            #print('continue 2')
            continue
        phone_no = row_list[6].value
        if phone_no:
            room_phone_dict[room] = phone_no

        residents.append(
            Resident(
                building=building_no, leader=leader, room=room, name=name, gender=gender, 
                id_no=id_no, age=age, phone_no=phone_no
            )
        )


    # 有些登记信息没有手机号，默认设置一个居委的号码
    default_phone_no = '11111111111'

    for r in residents:
        if not r.phone_no:
            if r.room in room_phone_dict.keys():
                r.phone_no = room_phone_dict[r.room]
            else:
                r.phone_no = default_phone_no
                # print(f'{r}')
        
        if len(str(r.phone_no)) != len(default_phone_no):
            r.phone_no = default_phone_no


        assert bool(r.phone_no)

    if not residents:
        raise RuntimeError(f'empty residents, building={building_no}')

    return residents, invalid_residents


if __name__ == '__main__':
    parser = argparse.ArgumentParser('')
    parser.add_argument('-f', type=str)
    args = parser.parse_args()
    wb = load_workbook(args.f, data_only=True)
    i = 0
    f = open('')
    for sheet in wb:
        ret = parse_sheet(sheet)
        if not ret:
            break
        residents, invalid_residents = ret
        if not residents:
            break
        for r in residents:
            if r.age >= 58:
                i += 1

        if invalid_residents:
            print(invalid_residents)

    print(f'total >= 58: {i}')
        
        